﻿using AutoMapper;
using GGGK.Film.IService;
using GGGK.Film.Models;
using GGGK.Film.Models.Dto;
using Microsoft.AspNetCore.Mvc;

namespace GGGK.Film.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FilmsController : ControllerBase
    {
        private readonly IFilmInfoService svc;
        private readonly IMapper mapper;

        public FilmsController(IFilmInfoService svc, IMapper mapper)
        {
            this.svc = svc;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="movieTitle"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public PagedResult<FilmInfoDto> Get(string movieTitle = "", int pageSize = 10, int pageIndex = 1)
        {
            string sql = @"select f.*,
	                        movie.MovieTitle,
	                        t.DictName as 'FilmType',
	                        m.DictName as 'FilmModel'
	                        from FilmInfo f
	                        inner join MovieInfo movie on f.MovieId = movie.Id
	                        inner join VW_Dict t on f.FilmTypeId = TRY_CONVERT(int,t.DictValue) and t.DictTypeName = '胶片种类'
	                        inner join VW_Dict m on f.FilmModelId = TRY_CONVERT(int,m.DictValue) and m.DictTypeName = '胶片类型'
	                        where 1=1";

            if (!string.IsNullOrEmpty(movieTitle)) sql += " and MovieTitle like @movieTitle";

            string totalSql = $"select count(*) from ({sql}) ff";

            int total = svc.ExecuteScalar<int>(totalSql, new { MovieTitle = $"%{movieTitle}%" });

            sql += @" order by CreateTime desc
                    offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<FilmInfoDto>(sql, new { MovieTitle = $"%{movieTitle}%", pageSize, pageIndex });

            return new PagedResult<FilmInfoDto>() { code = 1, msg = "成功", data = data, total = total };
        }
    }
}
